package com.dyna.gateway.filter.security;

import com.alibaba.fastjson.JSON;
import com.dyna.constants.SysConstant;
import com.dyna.core.utils.IpUtil;
import com.dyna.domain.resp.R;
import com.dyna.gateway.adapter.ServerHttpRequestAdapter;
import com.dyna.gateway.config.BlackListConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 黑名单过滤器
 *
 * @author admin
 */
@Order(-100)
@Component
public class BlackListUrlFilter implements GlobalFilter, Ordered
{
    private static final Logger log = LoggerFactory.getLogger(BlackListUrlFilter.class);

    private final BlackListConfig blackListConfig;

    @Autowired
    public BlackListUrlFilter(BlackListConfig blackListConfig) {
        this.blackListConfig = blackListConfig;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpServletRequest httpRequest = ServerHttpRequestAdapter.adapt(exchange.getRequest());
        String ipAddr = IpUtil.getIpAddr(httpRequest);
        //是否黑名单
        if (isBlacklisted(ipAddr)) {
            log.info("请求ip【{}】属于黑名单，已经被拦截了。", ipAddr);
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN);
            return response.writeWith(
                    Mono.just(response.bufferFactory().wrap(JSON.toJSONBytes(R.fail(SysConstant.BLACK_IP_ERROR_INFO)))));
        }
        return chain.filter(exchange);
    }

    private boolean isBlacklisted(String ip) {
        List<String> blacklistIps = blackListConfig.getIps();
        if (blacklistIps == null || blacklistIps.isEmpty()) {
            return false;
        }
        return blacklistIps.contains(ip);
    }

    @Override
    public int getOrder() {
        return -100;
    }

}



